import { request } from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage'
import { Login, Logout, REMOVE_USER } from '../constants'

// 提供一个 action creator => 返回一个函数(异步)
export const login = formObj => {
  return async dispatch => {
    // 1. 消化异步
    const res = await request.post('/authorizations', formObj)
    // console.log(res.data.data.token)
    const token = res.data.data.token

    // 往本地存储存
    setToken(token)

    // 2. dispatch(对象)
    // redux 中存储
    dispatch({
      type: Login,
      payload: token
    })
  }
}

export const logout = () => {
  return dispatch => {
    // 清本地存储
    removeToken()
    // 清除 redux - user 存储
    dispatch({ type: REMOVE_USER, })
    // 清除 redux 存储
    dispatch({ type: Logout })
  }
}